<?php

namespace App\Foundation\Utils;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Hmac\Sha256;

class JwtAssistant
{
    public $algorithm = 'HS256';
    public $secret = 'default';

    public function __construct($secret = 'default', $algorithm = 'HS256')
    {
        $this->secret = $secret;
        $this->algorithm = $algorithm;
    }


    public function getTokenSting(array $data)
    {
        $builder = (new Builder())->setHeader('alg', $this->algorithm);

        foreach ($data as $key => $value) {
            $builder->set($key, $value);
        }

        switch ($this->algorithm) {
            case 'HS256':
            default:
                $builder->sign(new Sha256(), new Key($this->secret));
                break;
        }

        $token = $builder->getToken();

        return $token->__toString();
    }

    /**
     * @param string $token
     * @param string|null $secret
     * @return bool|\Lcobucci\JWT\Token
     */
    public function verifyToken(string $token, string $secret = null)
    {
        $secret = is_null($secret) ? $this->secret : $secret;
        $tokenInfo = (new \Lcobucci\JWT\Parser())->parse($token);

        $signature = $tokenInfo->verify(new \Lcobucci\JWT\Signer\Hmac\Sha256(), $secret);
        if (!$signature) {
            return false;
        }
        return $tokenInfo;
    }
}
